package com.scr1pt.extension

import com.scr1pt.extension.enum.EHashType
import java.security.MessageDigest
import kotlin.experimental.and

/**
 * 说明: 字节扩展
 *
 * 创建者: tum0r
 *
 * 时间: 2021/8/21 16:56
 */

/**
 * 获取字节数组的散列值
 *
 * @param[type] 散列值类型
 */
@JvmOverloads
fun ByteArray.hash(type: EHashType = EHashType.SHA256): String {
    val result = StringBuilder()
    if (this.isNotEmpty()) {
        val messageDigest = MessageDigest.getInstance(type.getType())
        val digest = messageDigest.digest(this)
        val b = 0xff.toByte()
        for (byte in digest) {
            val hex = (byte and b).toString(16)
            if (hex.length == 1) result.append("0")
            result.append(hex)
        }
    }
    return result.toString()
}

/**
 * 获取IP地址的Int类型表示
 */
fun ByteArray.getIPInt(): Int {
    val intArray = IntArray(this.size)
    for (b in this.indices) intArray[b] = this[b].toPositiveInt()
    return intArray.getIPInt()
}

/**
 * 将Byte类型转为正数形式
 */
fun Byte.toPositiveInt(): Int = this.toInt() + if (this < 0) 256 else 0